package com.ls.cameraxtest;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.io.File;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.PermissionChecker;
import androidx.navigation.NavBackStackEntry;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

public class MainActivity extends AppCompatActivity {

    /**导航控制*/
    private NavController controller;
    /**悬浮按钮*/
    private FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        fab = findViewById(R.id.fab);
        //去拍照
        fab.setOnClickListener(this::toCamera);
    }

    /**
     * 进行拍照操作
     */
    private void toCamera(View view) {
        NavBackStackEntry navBackStackEntry = getNavControl().getCurrentBackStackEntry();
        if (navBackStackEntry != null && (navBackStackEntry.getDestination().getId() == R.id.Camera1Fragment ||
                navBackStackEntry.getDestination().getId() == R.id.Camera2Fragment)) {
            Snackbar.make(view, "拍完照了？那我们回去", Snackbar.LENGTH_LONG)
                    .setAction("好勒", v -> getNavControl().popBackStack()).show();
        } else {
            Snackbar.make(view, "去拍个照吧？", Snackbar.LENGTH_LONG)
                    .setAction("好勒", v -> goCamera(1)).show();
        }
    }

    /**
     * 跳转导航控制
     */
    private NavController getNavControl() {
        if (controller == null) {
            controller = Navigation.findNavController(this, R.id.nav_host_fragment);
        }
        return controller;
    }

    /**
     * 去拍摄
     *
     * @param type 1 就版本api 2 cameraX
     */
    public void goCamera(int type) {
        if (hadPermission()) {
            //去拍照
            if (type == 1) {
                getNavControl().navigate(R.id.action_FirstFragment_to_Camera1Fragment);
            } else {
                getNavControl().navigate(R.id.action_FirstFragment_to_Camera2Fragment);
            }
        } else {
            Snackbar.make(fab, "此功能需要摄像头和文件操作权限！", Snackbar.LENGTH_LONG)
                    .setAction("去授权", v -> {
                        Intent intent = new Intent();
                        intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }).show();
        }
    }

    /**
     * 拍照相关权限
     */
    private String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    /**
     * 判断是否有相关权限
     */
    private boolean hadPermission() {
        for (String p : permissions) {
            if (PermissionChecker.checkCallingOrSelfPermission(this, p) != PermissionChecker.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(permissions, 110);
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        NavBackStackEntry navBackStackEntry =  getNavControl().getCurrentBackStackEntry();
        if (navBackStackEntry != null && (navBackStackEntry.getDestination().getId() == R.id.Camera1Fragment ||
                navBackStackEntry.getDestination().getId() == R.id.Camera2Fragment)) {
            getNavControl().popBackStack();
            return true;
        }
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_camera1) {
            goCamera(1);
            return true;
        } else if (id == R.id.action_camera2) {
            goCamera(2);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * 保存图片到相册
     */
    public void saveImgToPics(Context context, String path) {
        //此处为耗时操作，需子线程操作
        new Thread(() -> {
            try {
                ContentResolver mResolver = context.getContentResolver();
                String insertImage = MediaStore.Images.Media.insertImage(mResolver, path, "name", "description");
                //需进行此转换操作，否则保存的图片时间为1970年的，会出现在相册的最上面
                String absPath = getRealPathFromUri(Uri.parse(insertImage), context);
                if (TextUtils.isEmpty(absPath)) {
                    return;
                }
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(absPath))));
                fab.post(() -> Toast.makeText(context, "保存相册成功：" + path, Toast.LENGTH_SHORT).show());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 得到绝对地址
     */
    private String getRealPathFromUri(Uri contentUri, Context context) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int columnIndex = 0;
            if (cursor != null) {
                columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(columnIndex);
            } else {
                return "";
            }
        } catch (Exception e) {
            return "";
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
}